package com.ohuang.fakescreen.window

import android.app.Activity
import android.content.Context
import android.content.pm.ActivityInfo
import android.graphics.PixelFormat
import android.os.Build
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.appcompat.app.ActionBar.LayoutParams
import com.ohuang.fakescreen.SmallWindowsHelper
import com.ohuang.fakescreen.dp2px

abstract class SmallWindow(open val activity: Activity) {

    protected lateinit var smallWindowsHelper: SmallWindowsHelper
    protected abstract fun createSmallView(): View

   open fun init(context: Context) {
        smallWindowsHelper = SmallWindowsHelper(context)
    }

   open fun showSmallWindow() {
        if (SmallWindowsHelper.requestPermission(activity)) {
            if (smallWindowsHelper.root == null) {
                smallWindowsHelper.attach(createSmallView())
                val mLayoutParams = smallWindowsHelper.mLayoutParams
                smallWindowsHelper.mLayoutParams =
                    initLayoutParam(mLayoutParams ?: defaultLayoutParam())
            } else {
                smallWindowsHelper.show()
            }
        }
    }

    private fun defaultLayoutParam(): WindowManager.LayoutParams {
        val mLayoutParams = WindowManager.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT
        )
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        }
        mLayoutParams.gravity = Gravity.NO_GRAVITY
        return mLayoutParams
    }

    open  fun initLayoutParam(layoutParams: WindowManager.LayoutParams): WindowManager.LayoutParams {
        return layoutParams
    }

    open fun isShow():Boolean{
        if (::smallWindowsHelper.isInitialized){
            return smallWindowsHelper.isShow
        }
        return false
    }

    open fun hideSmallWindow() {
        smallWindowsHelper.hide()
    }
}